const app = require("express")();
const server = require("http").createServer(app);
const io = require("socket.io")(server);

server.listen(9898);
console.log("创建socket.io服务");

io.on("connection", (socket) => {

  // 创建房间
  socket.on("joinRoom", (room) => {
    socket.join(room, () => {
      socket.emit("create", room);
    });
  });

  // 视频通信
  socket.on("signal", (message, room) => {
    socket.to(room).emit("signal", message);
  });

  socket.on("ice", (message, room) => {
    socket.to(room).emit("ice", message);
  });

  // 客户端断开
  socket.on("disconnecting", () => {
    const rooms = Object.keys(socket.rooms);
    console.log(rooms[0] + "离开房间");
    socket.to(rooms[0]).emit("leaveRoom", rooms[0]);
  });
  
  // 接受消息打电话
  socket.on('call', (msg, room) => {
    socket.to(room).emit('call', msg)
  })
});
